// router/index.js
import React, { useEffect } from "react";
import { useRoutes, Navigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { fetchMenuItems } from "@/store/modules/menus";
import { generateRoutes } from "./module/generateRoutes";
import Layout from "@/pages/Layout";
import Login from "@/pages/Login";
import AuthRoute from "@/components/AuthRoute";
const RouterWrapper = () => {
  const dispatch = useDispatch();
  const menus = useSelector((state) => state.menus.items);

  console.log("menus", menus);

  useEffect(() => {
    dispatch(fetchMenuItems());
  }, [dispatch]);

  const childRoutes = generateRoutes(menus);

  // 加默认首页重定向
  childRoutes.unshift({
    path: "",
    element: <Navigate to="/home" replace />,
  });

  const staticRoutes = [
    {
      path: "/login",
      element: <Login />,
    },
    {
      path: "/",
      element: (
        <AuthRoute>
          <Layout />
        </AuthRoute>
      ),
      children: childRoutes,
    },
  ];

  return useRoutes(staticRoutes);
};

export default RouterWrapper;
